package com.mimc.framework.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Aop;
import com.mimc.framework.manager.vo.MinioConf;
import com.mimc.service.ShSysConfigService;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class MinioManager {
    private static MinioManager manager = new MinioManager();
    private MinioManager(){}
    public static MinioManager me(){
        return manager;
    }
    private MinioClient minio;

    public MinioClient getMinio(){
        if(minio==null){
            init();
        }
        return minio;
    }
    public MinioConf getMinioConf(){
        ShSysConfigService shSysConfigService= Aop.get(ShSysConfigService.class);
        String configValue=shSysConfigService.getConfigValueByKey("upload.settings");
        JSONObject jsonObj= JSON.parseObject(configValue);
        JSONObject engine=jsonObj.getJSONObject("engine");
        MinioConf minioConf=engine.getObject("minio",MinioConf.class);
        return minioConf;
    }
    public void init(){
        MinioConf minioConf=getMinioConf();
        this.minio=MinioClient.builder()
                .endpoint(minioConf.getDomain())
                .credentials(minioConf.getKey(), minioConf.getSecret())
                .build();
        try {
            this.minio.ignoreCertCheck();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        log.info("初始化Minio");
    }
}
